package com.moss.street.market;


import java.io.IOException;
import java.sql.Connection;
import java.sql.Date;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Calendar;
import java.util.List;

import javax.servlet.Servlet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * A controller servlet for the view presented by the BookStall.jsp web page.
 *  
 * @author drusk
 */
public class UpdateBookingServlet extends HttpServlet implements Servlet {
	
	

    /* (non-Javadoc)
     * @see javax.servlet.http.HttpServlet#doPost(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
     */
   protected void doPost(HttpServletRequest request, HttpServletResponse response)
           throws ServletException, IOException
   {

       HttpSession session = request.getSession();
       StallsBean stallBooked = null;
       String username = null;
       String reservationDate = null;
       
       if (session != null)
       {
           stallBooked = (StallsBean)session.getAttribute("stall");
           reservationDate = (String)session.getAttribute("marketday");
           username = (String)session.getAttribute("username");
       }

       if ((stallBooked != null) && (username != null) && (reservationDate != null))
       {   
    	   Connection conn = DerbyDatabase.getConnInstance();
           
    	   Calendar currentDate = Calendar.getInstance();
    	   SimpleDateFormat dfdb= new SimpleDateFormat("yyyy-MM-dd");
    	   String dateNow = dfdb.format(currentDate.getTime());
 
           int numRows = DerbyDatabase.bookingsUpdate(conn, username, stallBooked.getStallNumber(),
        		   reservationDate, "N", dateNow);
           boolean success = false;

           if (numRows == 1)
           {
               success = true;
           }
           if (success)
           {
               BookingsBean[] bookingsHistory = DerbyDatabase.fetchBookings(conn, username);
               request.getSession().setAttribute("bookingHistory", bookingsHistory);
               request.setAttribute("reservationDate", reservationDate);
               getServletContext().getRequestDispatcher("/GoodBye.jsp").forward(request, response); 
           }
           else
           {
               getServletContext().getRequestDispatcher("/Error.jsp").forward(request, response); 

           }
       }
       // problem with all parameters passed being non-null
       else
       {
           getServletContext().getRequestDispatcher("/Error.jsp").forward(request, response);
       }
   }
       protected void doGet(HttpServletRequest request, HttpServletResponse response)
       throws ServletException, IOException
   {
           doPost(request,response);
   }
}
